const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://app/jsmodules/sbLibraryUtils.jsm");
Cu.import("resource://app/jsmodules/sbProperties.jsm");

// check that gMM exists
if (typeof gMM == "undefined") {
  var gMM = Cc["@songbirdnest.com/Songbird/Mediacore/Manager;1"].getService(Ci.sbIMediacoreManager);
}


// Make a namespace.
if (typeof Trackinfo == 'undefined') {
  var Trackinfo = {};
}

/**
 * Controller for pane.xul
 */
Trackinfo.PaneController = {

  /**
   * Called when the pane is instantiated
   */
  onLoad: function() {
  
    gMM.addListener(this);
  
    this._initialized = true;
    
    // Make a local variable for this controller so that
    // it is easy to access from closures.
    var controller = this;
    

    this._descField = document.getElementById("description-field");
	gMM.addListener(this);
	
    // Por si hay una track activo al cargarse el pane...
    if ((gMM.status.state == Ci.sbIMediacoreStatus.STATUS_PLAYING) ||
        (gMM.status.state == Ci.sbIMediacoreStatus.STATUS_PAUSED) ||
        (gMM.status.state == Ci.sbIMediacoreStatus.STATUS_BUFFERING)) {
      var artistName = gMM.sequencer.currentItem.getProperty(SBProperties.artistName);
      this._descField.value = artistName;
    }
  },
  
  /**
   * Called when the pane is about to close
   */
  onUnLoad: function() {
    this._initialized = false;
  },
  
  /**
   * Load the Display Pane documentation in the main browser pane
   */
  loadHelpPage: function() {
    // Ask the window containing this pane (likely the main player window)
    // to load the display pane documentation
    top.loadURI("http://wiki.songbirdnest.com/Developer/Articles/Getting_Started/Display_Panes");
  },
  
  onMediacoreEvent: function(ev) {
    switch (ev.type) {
      case Ci.sbIMediacoreEvent.TRACK_CHANGE:
        var artistName = ev.data.getProperty(SBProperties.artistName);
        this._descField.value = artistName;
        break;
      case Ci.sbIMediacoreEvent.STREAM_END:
      case Ci.sbIMediacoreEvent.STREAM_STOP:
        this._descField.value = "";
        break;
    }
  },
};

window.addEventListener("load", function(e) { Trackinfo.PaneController.onLoad(e); }, false);
window.addEventListener("unload", function(e) { Trackinfo.PaneController.onUnLoad(e); }, false);